package com.lmm.cg.zjgcg.pages.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.lmm.cg.zjgcg.MainApplication;
import com.lmm.cg.zjgcg.R;
import com.lmm.cg.zjgcg.config.AppKey;
import com.lmm.cg.zjgcg.config.AppKeyValueUtils;
import com.lmm.cg.zjgcg.pages.AppBaseActivity;
import com.lmm.dresswisdom.lmmframe.components.dialog.DefaultWaitDialog;
import com.lmm.dresswisdom.lmmframe.reactnative.annotation.RNPlugin;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.qr.print.PrintPP_CPCL;

import java.nio.channels.InterruptedByTimeoutException;
import java.util.Set;

/**
 * 蓝牙设备列表
 */
@Route(path = "/page/devicelist")
public class DeviceListActivity extends AppBaseActivity implements View.OnClickListener {

    ListView listView;
    RelativeLayout relSearch;
    TextView tvSearchState;

    TextView tvTitle;
    ImageView ivBack;
    LinearLayout relTopbar;

    private PrintPP_CPCL printPP_cpcl;
    private boolean isConnected = false;
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothService mService = null;

    // 蓝牙设备
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    DefaultWaitDialog defaultWaitDialog;

    public void showDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (!defaultWaitDialog.isShowing()) {
            LogUtils.write("show");
            defaultWaitDialog.ShowDialog();
        }
    }

    public void hideDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (defaultWaitDialog.isShowing()) {
            LogUtils.write("hide");
            defaultWaitDialog.HideDialog();
            defaultWaitDialog = null;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicelist);
        initView();
        setBluetoothAdapter();

    }



    private void initView() {
        listView = (ListView) findViewById(R.id.lv_devices);
        relSearch = (RelativeLayout) findViewById(R.id.rel_search);
        relSearch.setOnClickListener(this);
        tvSearchState = (TextView) findViewById(R.id.tv_searcState);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("蓝牙连接");
        ivBack = (ImageView) findViewById(R.id.ivBack);
        relTopbar = (LinearLayout) findViewById(R.id.relTopbar);
        relTopbar.getLayoutParams().height = relTopbar.getLayoutParams().height + getStatusBarHeight();
        relTopbar.setPadding(relTopbar.getPaddingLeft(), getStatusBarHeight(), relTopbar.getPaddingRight(), relTopbar.getPaddingBottom());
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void setBluetoothAdapter() {
        printPP_cpcl = new PrintPP_CPCL();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            ToastUtils.showToastShort("蓝牙设备不可用");
            finish();
            return;
        }

        //设置数据源
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);
        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        }

        listView.setAdapter(mNewDevicesArrayAdapter);
        listView.setOnItemClickListener(mDeviceClickListener);
    }

    //连接设备
    private void connectDevice(String info) {
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        String address = info.substring(info.length() - 17);
        String name = info.substring(0, (info.length() - 17));

        if (name.length() > 0 ) {
            Intent mintent = new Intent();
            mintent.putExtra("address", address);
            mintent.putExtra("name", name);
            setResult(RESULT_OK, mintent);
            finish();
        }
// else {
//            AppKeyValueUtils.setValue(AppKey.BlueToothAddress, address);

//            ((MainApplication) getApplication()).connectBlueTooth(address, new BluetoothCallBack() {
//                @Override
//                public void connectSuccess(String name, String address) {
//
//                    AppKeyValueUtils.setValue(AppKey.BlueToothName , name);
//
//                    Intent mintent = new Intent();
//                    mintent.putExtra("address", address);
//                    mintent.putExtra("name", name);
//                    setResult(RESULT_OK, mintent);
//                    finish();
//                }
//            });
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
        this.unregisterReceiver(mReceiver);
    }

    @Override
    public void onClick(View v) {
        if (v == relSearch) {
            showDefaultDialog();
            mBluetoothAdapter.startDiscovery();
        }
    }

    // The on-click listener for all devices in the ListViews
    private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }


            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();

            connectDevice(info);
            // String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
//            Intent intent = new Intent();
//            intent.putExtra(EXTRA_DEVICE_ADDRESS, info);

            // Set result and finish this Activity
//            setResult(Activity.RESULT_OK, intent);
//            finish();
        }
    };


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    LogUtils.write("新设备");
                    LogUtils.write(device.getName());
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                hideDefaultDialog();
                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    String noDevices = getResources().getText(R.string.none_found).toString();
//                    mNewDevicesArrayAdapter.add(noDevices);
                    LogUtils.write("没有新设备");
                }
            }
        }
    };
}
